package self.xine.basic.thread.communication;

import self.xine.basic.thread.entity.LockSharedObject;

/**
 * 多线程间的通信安全，是通过加锁的方式实现
 * 
 * 
 * 
 * @author xine
 * @date 2018年9月8日
 */
public class LockTest{
		
	public static void main(String[] args) {
		LockSharedObject sharedObject = new LockSharedObject();

		Thread t1 = new Thread(new LockSubRunnable(sharedObject),"线程1");
		Thread t2 = new Thread(new LockAddRunnable(sharedObject),"线程2");
				
		t1.start();
		t2.start();
			
		long timeStart = System.currentTimeMillis();
		while(System.currentTimeMillis() - timeStart < 5000) {
			System.out.println(t1.getName() + " " + t1.getState().name() + " --- " + t2.getName() + " " + t2.getState().name());
		}
				
		try {
			t1.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		try {
			t2.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println(sharedObject.getCount());
		
	}

}

class LockSubRunnable implements Runnable {
	private LockSharedObject sharedObject;
	
	public LockSubRunnable(LockSharedObject sharedObject) {
		this.sharedObject = sharedObject;	
	}
	
	@Override
	public void run() {
		while(sharedObject.getCount() >= 0) {
			sharedObject.sub(1);			
			System.out.println(Thread.currentThread().getName() + " : " + sharedObject.getCount());	
		}				
	}
}

class LockAddRunnable implements Runnable {
	private LockSharedObject sharedObject;
		
	public LockAddRunnable(LockSharedObject sharedObject) {
		this.sharedObject = sharedObject;
	}
	
	@Override
	public void run() {
		while(sharedObject.getCount() <= 10) {
			sharedObject.add(1);			
			System.out.println(Thread.currentThread().getName() + " : " + sharedObject.getCount());

		}			
	}
}
